package jsyf.oa.service.email;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jsyf.com.util.FastJsonConvert;
import jsyf.oa.dao.email.EmailDao;
import jsyf.oa.dao.email.InboxDao;
import jsyf.oa.dao.email.SentEmailDao;
import jsyf.oa.entity.email.EmailEntity;
import jsyf.oa.facade.email.SentEmailFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.List;

/**
 * Created by LT on 2018/3/7.
 */
@Service
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class SentEmailService implements SentEmailFacade {
    @Autowired
    private SentEmailDao sentEmailDao;

    @Override
    public JSONObject findSentList(String createUserId,String searchKey, int requestPage,int pageSize) {
        JSONObject result = new JSONObject();
        JSONObject objSendData = new JSONObject();
        StringBuilder sbCondition =new StringBuilder();
        sbCondition.append(" AND email.DRAFT = 0 AND email.CREATE_USER_ID ='"+createUserId+"' ");
        if (!StringUtils.isBlank(searchKey)) {
            searchKey = searchKey.trim();
            sbCondition.append(" AND email.subject LIKE " + "'%" + searchKey + "%' ");
        }
        List<JSONObject> records = sentEmailDao.getListByPage(sbCondition.toString(), requestPage, pageSize);
        int recordCount = sentEmailDao.getListByPageCount(sbCondition.toString());
        int recordSize = Integer.valueOf(pageSize).intValue();
        int pageCount = 0;
        if (recordCount < recordSize) {
            pageCount = 1;
        } else {
            double flag = Math.ceil(recordCount / recordSize);
            pageCount = ((int) flag) + 1;
        }
        if (recordCount == 0) {
            pageCount = 0;
        }
        //子对象
        objSendData.put("recordCount", recordCount);
        objSendData.put("pageCount", pageCount);
        objSendData.put("requestPage", 1);
        result.put("pager", objSendData);
        // 子数组对象
        result.put("records", records);
        return result;
    }

    @Override
    public JSONObject findSentById(String jsonData){
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
         String emailId=jsonParams.getString("id");
        List<JSONObject> receivers=sentEmailDao.getByEmailReceiver(emailId, "0");
        List<JSONObject> copiers=sentEmailDao.getByEmailReceiver(emailId, "1");
        List<JSONObject> attaches=sentEmailDao.getByAttaches(emailId);
        JSONObject records = sentEmailDao.getJSONById(emailId);
        records.put("receivers",receivers);
        records.put("copiers",copiers);
        records.put("attaches",attaches);
        return records;
}

    @Override
    public Boolean removeSentById(String id) {
        return sentEmailDao.removeByCondition(" AND ID = ? ", new String[]{id})>0;
    }
}
